package com.xagent.engine.hook.impl;


import com.xagent.engine.hook.HookInfo;
import com.xagent.engine.hook.MethodInfo;

import java.util.HashMap;

public class HookInfoImpl implements HookInfo {
    private String className;
    // key是方法名+方法描述符
    private HashMap<String, MethodInfo> methodInfoHashMap;

    public HookInfoImpl(String className) {
        this.className = className;
        methodInfoHashMap = new HashMap<String, MethodInfo>();
    }

    @Override
    public String getClassName() {
        return className;
    }

    @Override
    public HashMap<String, MethodInfo> getMethodInfoHashMap() {
        return methodInfoHashMap;
    }

    @Override
    public void addMethodInfo(MethodInfo methodInfo) {
        if (methodInfo.getMethodDescriptor() == null || methodInfo.getMethodName() == null) {
            return;
        }

        if (!methodInfoHashMap.containsKey(methodInfo.getMethodDescriptor()) && className.equals(methodInfo.getClassName())) {
            methodInfoHashMap.put(methodInfo.getMethodName() + methodInfo.getMethodDescriptor(), methodInfo);
        }

        if ("".equals(methodInfo.getClassName()) || methodInfo.getClassName() == null) {
            methodInfo.setClassName(className);
            methodInfoHashMap.put(methodInfo.getMethodName() + methodInfo.getMethodDescriptor(), methodInfo);
        }
    }

    @Override
    public boolean needEnhance(String method) {
        if (methodInfoHashMap.get(method) != null) return true;
        return false;
    }

    @Override
    public boolean isHook(String method) {
        if (methodInfoHashMap.containsKey(method)) return true;
        return false;
    }

    @Override
    public MethodInfo getAMethodInfo(String methodWithoutReturnType) {
        if (methodInfoHashMap.containsKey(methodWithoutReturnType)) return methodInfoHashMap.get(methodWithoutReturnType);
        return null;
    }
}
